<?php

namespace Admin\Controller;

use Zend\Mvc\Controller\AbstractActionController;
use Zend\View\Model\ViewModel;
use Admin\Model\Tintuc;
use Admin\Form\TintucForm;
use Zend\Db\Sql\Select;
use Zend\Paginator\Paginator;
use Zend\Paginator\Adapter\Iterator as paginatorIterator;
use Zend\Session\Container;
use Zend\Validator\File\Size;
use Zend\Validator\File\Extension;


class TintucController extends AbstractActionController {

    protected $tintucTable;

	public function kiemtra(){
		$module = "tintuc";
		$controller = $this->params('controller');
		$action = $this->params('action');
		
		$sessionModule = new Container('module');
		$sessionController = new Container('controller');
		$sessionAction = new Container('action');
		$sessionModule->lastModule = $module;
		$sessionController->lastController = $controller;
		$sessionAction->lastAction = $action;
		
		$sessionUser = new Container('user');
		if(!$sessionUser->tendangnhap){
			return $this->redirect()->toRoute('auth');
		}
		else if($sessionUser->tendangnhap && $sessionUser->quyen != 1){
			return $this->redirect()->toRoute('home');
		}
	}
    public function indexAction() {
		
		$this->kiemtra();
		$request = $this->getRequest();
		if ($request->isPost()) {
			$order_by = $request->getPost('order_by');
			$order = $request->getPost('order');
			$page = $request->getPost('page');
			$ngaydang = $request->getPost('ngaydang');
			$keyword = $request->getPost('keyword');
			$limit = $request->getPost('limit');
		}
		else{
			$order_by = $this->params()->fromRoute('order_by') ?
                $this->params()->fromRoute('order_by') : 'id';
			$order = $this->params()->fromRoute('order') ?
                $this->params()->fromRoute('order') : Select::ORDER_DESCENDING;
        	$page = $this->params()->fromRoute('page') ? (int) $this->params()->fromRoute('page') : 1;
			$ngaydang = "";
			$keyword = "";
			$limit = "";
		}
        $select = new Select();

        if($limit=="")
		{
			if($ngaydang!="" && $keyword!="")
				$tintucs = $this->getTintucTable()->fetchAll($select->where('ngaydang like "%'.$ngaydang.'%" AND (tieude like "%'.$keyword.'%" OR tenchuyenmuc like "%'.$keyword.'%" OR hoten like "%'.$keyword.'%" )')->order($order_by . ' ' . $order));
			else if($ngaydang!="" && $keyword=="")
				$tintucs = $this->getTintucTable()->fetchAll($select->where('ngaydang like "%'.$ngaydang.'%"')->order($order_by . ' ' . $order));
			else 
				$tintucs = $this->getTintucTable()->fetchAll($select->where('tieude like "%'.$keyword.'%" OR tenchuyenmuc like "%'.$keyword.'%" OR hoten like "%'.$keyword.'%" ')->order($order_by . ' ' . $order));
		}
		else if($limit!="")
		{
			if($ngaydang!="" && $keyword!="")
				$tintucs = $this->getTintucTable()->fetchAll($select->where('ngaydang like "%'.$ngaydang.'%" AND (tieude like "%'.$keyword.'%" OR tenchuyenmuc like "%'.$keyword.'%" OR hoten like "%'.$keyword.'%" )')->order($order_by . ' ' . $order)->limit($limit));
			else if($ngaydang!="" && $keyword=="")
				$tintucs = $this->getTintucTable()->fetchAll($select->where('ngaydang like "%'.$ngaydang.'%"')->order($order_by . ' ' . $order)->limit($limit));
			else 
				$tintucs = $this->getTintucTable()->fetchAll($select->where('tieude like "%'.$keyword.'%" OR tenchuyenmuc like "%'.$keyword.'%" OR hoten like "%'.$keyword.'%" ')->order($order_by . ' ' . $order)->limit($limit));
		}
		
		else
        	$tintucs = $this->getTintucTable()->fetchAll($select->order($order_by . ' ' . $order));
        $itemsPerPage = 7;

        $tintucs->current();
        $paginator = new Paginator(new paginatorIterator($tintucs));
        $paginator->setCurrentPageNumber($page)
                ->setItemCountPerPage($itemsPerPage)
                ->setPageRange(7);

        return new ViewModel(array(
                    'order_by' => $order_by,
                    'order' => $order,
                    'page' => $page,
                    'paginator' => $paginator,
					'ngaydang' => $ngaydang,
					'keyword' => $keyword,
                ));
				
		array_map('unlink', glob('data/*'));

        return array();
    }

    public function addAction() {
		
		$this->kiemtra();
		
		$dbAdapter = $this->getServiceLocator()->get('Zend\Db\Adapter\Adapter');
        $form = new TintucForm($dbAdapter);
        $form->get('submit')->setAttribute('value', 'Thêm');
		$viewModel = new ViewModel();
        $request = $this->getRequest();
        if ($request->isPost()) {
            $tintuc = new Tintuc();
            $form->setInputFilter($tintuc->getInputFilter());
            $nonFile = $request->getPost()->toArray();
            $File    = $this->params()->fromFiles('hinhanh');
			$data = array_merge_recursive(
                 $nonFile,
                 array('hinhanh'=> 'images/upload/'.$File['name'])
             );

            $form->setData($data);
            if ($form->isValid()) {
                $tintuc->exchangeArray($form->getData());
				if($this->getTintucTable()->check_exists($_POST['tieude'],0)){
					$viewModel->setVariable('error', 'Tiêu đề đã tồn tại');
					$viewModel->setVariable('form', $form);
					return $viewModel;
				}
				
				else{
					
					$size = new Size(array('max'=>5000000)); //minimum bytes filesize
					
					$extension = new Extension(array("extension" => array("jpg", "png", "gif", "jpeg")));
     
					$adapter = new \Zend\File\Transfer\Adapter\Http(); 
					//validator can be more than one...
					$adapter->setValidators(array($size,$extension), $File['name']);
					 
					if (!$adapter->isValid()){
						$dataError = $adapter->getMessages();
						$error = array();
						foreach($dataError as $key=>$row)
						{
							$error[] = $row;
						} //set formElementErrors
						$form->setMessages(array('hinhanh'=>$error ));
					} else {
						$adapter->setDestination('public/images/upload');
						if ($adapter->receive($File['name'])) {
							$this->getTintucTable()->saveTintuc($tintuc);
	
							// Redirect to list of users
							return $this->redirect()->toRoute('tintuc');
						}
					}  
					
					
				}
            }
        }

        return array('form' => $form);
    }

    public function editAction() {
		$this->kiemtra();
		
        $id = (int) $this->params('id');
        if (!$id) {
            return $this->redirect()->toRoute('tintuc', array('action' => 'add'));
        }
		$viewModel = new ViewModel();
        $tintuc = $this->getTintucTable()->getTintuc($id);
		if (!$tintuc) {
            return $this->redirect()->toRoute('tintuc');
        }

		$dbAdapter = $this->getServiceLocator()->get('Zend\Db\Adapter\Adapter');
        $form = new TintucForm($dbAdapter);
        $form->bind($tintuc);
        $form->get('submit')->setAttribute('value', 'Sửa');
		

        $request = $this->getRequest();
        if ($request->isPost()) {
            //$form->setData($request->getPost());
			$File    = $this->params()->fromFiles('hinhanhmoi');
			
            if ($form->isValid()) {
				
				if($this->getTintucTable()->check_exists($_POST['tieude'],$id)){
					$viewModel->setVariable('error', 'Tiêu đề đã tồn tại');
					$viewModel->setVariable('id', $id);
					$viewModel->setVariable('form', $form);
					return $viewModel;
				}
				
				else{
					if($File['name']!="")
					{
						$size = new Size(array('max'=>5000000)); //minimum bytes filesize
					
						$extension = new Extension(array("extension" => array("jpg", "png", "gif", "jpeg")));
		 
						$adapter = new \Zend\File\Transfer\Adapter\Http(); 
						//validator can be more than one...
						$adapter->setValidators(array($size,$extension), $File['name']);
						 
						if (!$adapter->isValid()){
							$dataError = $adapter->getMessages();
							$error = array();
							foreach($dataError as $key=>$row)
							{
								$error[] = $row;
							} //set formElementErrors
							$form->setMessages(array('hinhanhmoi'=>$error ));
						} else {
							$adapter->setDestination('public/images/upload');
							if ($adapter->receive($File['name'])) {
								$hinhanhmoi = 'images/upload/'.$File['name'];
								$this->getTintucTable()->capnhat($id,$_POST['tieude'],$_POST['mota'],$_POST['noidung'],$_POST['hinhanh'],$_POST['chuyenmuc'],$_POST['trangthai'],$_POST['tinnoibat'],$hinhanhmoi);
								return $this->redirect()->toRoute('tintuc');
							}
						}  
					}
					else
					{
						$this->getTintucTable()->capnhat($id,$_POST['tieude'],$_POST['mota'],$_POST['noidung'],$_POST['hinhanh'],$_POST['chuyenmuc'],$_POST['trangthai'],$_POST['tinnoibat']);
					}
					// Redirect to list of users
					return $this->redirect()->toRoute('tintuc');
				}
            }
        }

        return array(
            'id' => $id,
            'form' => $form,
        );
    }

    public function deleteAction() {
		$this->kiemtra();
		
		$request = $this->getRequest();
		if ($request->isPost()) {
			$id = $request->getPost('data');
			if (!$id) {
            	return $this->redirect()->toRoute('tintuc');
        	}
			else{
				$this->getTintucTable()->deleteTintuc($id);
				// Redirect to list of users
				return $this->redirect()->toRoute('tintuc');
			}
		}

        return array(
            'id' => $id,
            'tintuc' => $this->getTintucTable()->getTintuc($id)
        );
    }
	public function updateAction() {
		$this->kiemtra();
		
		$request = $this->getRequest();
		if ($request->isPost()) {
			$xoa = $request->getPost('xoa');
			$phathanh = $request->getPost('phathanh');
			$an = $request->getPost('an');
			$noibat = $request->getPost('noibat');
			$binhthuong = $request->getPost('binhthuong');
			if ($xoa!="") {
            	$this->getTintucTable()->xoaTintuc($xoa);
				return $this->redirect()->toRoute('tintuc');
        	}
			else if ($phathanh!="") {
            	$this->getTintucTable()->phathanhTintuc($phathanh);
				return $this->redirect()->toRoute('tintuc');
        	}
			else if ($an!="") {
            	$this->getTintucTable()->anTintuc($an);
				return $this->redirect()->toRoute('tintuc');
        	}
			else if ($noibat!="") {
            	$this->getTintucTable()->noibatTintuc($noibat);
				return $this->redirect()->toRoute('tintuc');
        	}
			else if ($binhthuong!="") {
            	$this->getTintucTable()->binhthuongTintuc($binhthuong);
				return $this->redirect()->toRoute('tintuc');
        	}
			else {
            	return $this->redirect()->toRoute('tintuc');
        	}
		}

        
    }

    public function getTintucTable() {
        if (!$this->tintucTable) {
            $sm = $this->getServiceLocator();
            $this->tintucTable = $sm->get('Admin\Model\TintucTable');
        }
        return $this->tintucTable;
    }

}
